package com.nearbymap.tooling;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nearbymap.model.XmlResponse;

@Service
public class XmlService {
	
	@Autowired
	private ConnectionFactory connectionFactory;

	public XmlResponse query(URL xmlServiceUrl) {
		HttpURLConnection connection = null;
		BufferedReader rd = null;
		StringBuilder sb = null;
		try {
			connection = connectionFactory.getServerConnection(xmlServiceUrl);
			rd = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			sb = new StringBuilder();
			java.lang.String line;
			while ((line = rd.readLine()) != null) {
				sb.append(line + '\n');
			}
			return new XmlResponse(sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} catch (ProtocolException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}
